const Sequelize = require('sequelize');
const DB = require("../config/dbconfig");
const commentRelationModel = require('./comment_rela_tab');
const triendModel = require('./triend_tab');
const userModel = require('./user_tab');

const commentModel = DB.define('comment_tab', {
    comment_id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      comment: "评论的id，主键",
      references: {
        model: 'comment_rela_tab',
        key: 'comment_id'
      }
    },
    create_time: {
      type: Sequelize.DATE,
      allowNull: true,
      comment: "评论的时间"
    },
    content: {
      type: Sequelize.STRING(255),
      allowNull: true,
      comment: "评论内容"
    },
    user_id: {
      type: Sequelize.INTEGER,
      allowNull: true,
      comment: "用户表的外键",
      references: {
        model: 'user_tab',
        key: 'user_id'
      }
    },
    triend_id: {
      type: Sequelize.INTEGER,
      allowNull: true,
      comment: "动态表的外键",
      references: {
        model: 'triend_tab',
        key: 'triend_id'
      }
    },
    parent_id: {
      type: Sequelize.INTEGER,
      allowNull: true,
      comment: "评论关系表的外键,父级评论的id"
    },
    is_delete:{
      type:Sequelize.INTEGER(2),
      comment:"是否删除"
    }
  }, {
    Sequelize,
    tableName: 'comment_tab',
    timestamps: false,
    indexes: [
      {
        name: "PRIMARY",
        unique: true,
        using: "BTREE",
        fields: [
          { name: "comment_id" },
        ]
      },
      {
        name: "user_comment",
        using: "BTREE",
        fields: [
          { name: "user_id" },
        ]
      },
      {
        name: "triend_comment",
        using: "BTREE",
        fields: [
          { name: "triend_id" },
        ]
      },
    ]
  });
  //多对多
  // commentModel.belongsToMany(commentModel, {
  //   through: commentRelationModel,
  //   as: 'parent_comments', // 定义一个别名，用于查询时引用
  //   foreignKey: 'comment_id'
  // })
  // commentModel.belongsToMany(commentModel, {
  //   through: commentRelationModel,
  //   as: 'child_comments', // 定义一个别名，用于查询时引用
  //   foreignKey: 'parent_id'
  // })
  //多对一
  commentModel.belongsTo(commentModel, {
    as: 'parent_comment',
    foreignKey: 'parent_id',
    // constraints: false, // 不强制要求父评论存在
    // scope: {
    //     parent_id: { [Sequelize.Op.ne]: null } // 添加条件，父评论ID不为空
    // }
  });
commentModel.belongsTo(userModel, { foreignKey: 'user_id' }); // 假设外键字段为 user_id
module.exports = commentModel
